import ConfigParser
import os
import shutil
import sys
import time
import copy_secret

import log


def publish_res():
    arg1 = "python publish_res.py "
    os.system(arg1)


def build_android(l_time):
    arg = "python build_android.py " + l_time
    os.system(arg)


def build_ios(l_time):
    arg = "python build_ios.py " + l_time
    os.system(arg)


def copy_secret_file():
    arg = "python copy_secret.py"
    os.system(arg)


def backup_src(l_time):
    log.debug("backup src begin")
    _time_path = os.path.abspath("./../publish/" + l_time)
    if os.path.exists(_time_path):
        shutil.rmtree(_time_path)
    os.mkdir(_time_path)
    _backup_src_zip = _time_path + os.sep + "backup.zip"
    _arg = "zip -9 -x -D *.jsc *DS_Store* -r " + _backup_src_zip + " ../src ../res"
    os.system(_arg)
    log.debug("backup src over")


cf = ConfigParser.ConfigParser()
cf.read("../conf/project.conf")
try:
    H_FILE_PATH = eval(cf.get("secret", "h_file_path"))
    H_DIST_FILE_PATH = eval(cf.get("secret", "h_dist_file_path"))
except ConfigParser.NoOptionError, e:
    print e
else:
    if len(sys.argv) == 2:
        _platform = sys.argv[1]
        _time = time.strftime("%Y_%m_%d_%H_%M_%S")
        publish_res()
        backup_src(_time)
        copy_secret.copy_h_file(H_FILE_PATH, H_DIST_FILE_PATH)
        if _platform == "android":
            build_android(_time)
        elif _platform == "ios":
            build_ios(_time)
        elif _platform == "all":
            build_android(_time)
            build_ios(_time)
        else:
            log.error("your package argument is wrong")
        copy_secret.revert_h_file(H_DIST_FILE_PATH)
    else:
        log.error("build argument numbers wrong!!")
